Popular Searches
Popular Course Categories
Popular Courses

Flutter Packages and Dependencies

Flutter Packages and Dependencies

Flutter Packages & Local Storage

Flutter Packages and Dependencies

Flutter packages and dependencies allow developers to add reusable functionality to Flutter applications without building every feature from scratch. Packages can provide features such as API communication, state management, Firebase integration, local storage, authentication, navigation, animations, device access, and more.

1. What is a Flutter Package?

A Flutter package is a reusable collection of Dart or Flutter code that can be added to a Flutter project. Packages help developers use existing functionality and reduce development time.

Example

Instead of creating an HTTP networking system from scratch, developers can use the http package.

import 'package:http/http.dart' as http;

Future<void> fetchData() async {
  final response = await http.get(
    Uri.parse('https://example.com/api/users'),
  );

  if (response.statusCode == 200) {
    print(response.body);
  }
}

2. What is a Dependency?

A dependency is an external package or library that a Flutter application requires to provide specific functionality.

For example, if an application uses the http package for API communication, then http is a dependency of the application.

Dependency Flow

Flutter Project
      |
      v
pubspec.yaml
      |
      v
Add Dependency
      |
      v
flutter pub get
      |
      v
Package Downloaded
      |
      v
Import Package
      |
      v
Use Package

3. Why Use Flutter Packages?

  • Reduce development time.
  • Reuse existing functionality.
  • Avoid writing common functionality from scratch.
  • Improve application development speed.
  • Use community-developed solutions.
  • Add advanced functionality easily.
  • Keep application architecture modular.
  • Integrate external services and APIs.

4. Packages vs Plugins

A plugin is a specialized type of package that provides access to platform-specific functionality such as camera, GPS, Bluetooth, notifications, or device information.

FeaturePackagePlugin
PurposeProvides reusable Dart or Flutter functionality.Provides access to platform-specific functionality.
Native CodeMay not require native code.Can communicate with native platform APIs.
Examplehttp, intlcamera, url_launcher
Platform AccessNot necessarily required.Commonly required.

5. The pubspec.yaml File

The pubspec.yaml file is one of the most important configuration files in a Flutter project. It contains project information, SDK constraints, dependencies, development dependencies, assets, fonts, and other configuration.

Basic Structure

name: my_flutter_app
description: A Flutter application

environment:
  sdk: ^3.0.0

dependencies:
  flutter:
    sdk: flutter

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true

6. Adding Dependencies

Application dependencies are placed inside the dependencies section.

dependencies:
  flutter:
    sdk: flutter
  http: ^1.0.0
  provider: ^6.0.0

In this example, http and provider are external dependencies.

7. dev_dependencies

The dev_dependencies section contains packages mainly used during development, testing, analysis, and code generation.

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_lints: ^6.0.0
Dependency TypePurpose
dependenciesPackages required by the application.
dev_dependenciesPackages mainly used during development and testing.
flutter_testTesting Flutter applications.
flutter_lintsRecommended linting rules.

8. Adding a Package Using flutter pub add

The easiest way to add a package is by using the flutter pub add command.

flutter pub add http

This command adds the package to the project's dependency configuration.

Another Example

flutter pub add provider

9. Adding a Package Manually

A package can also be added manually inside pubspec.yaml.

dependencies:
  flutter:
    sdk: flutter
  http: ^1.0.0

After modifying the file, run:

flutter pub get

10. What is flutter pub get?

The flutter pub get command retrieves and resolves the dependencies specified in pubspec.yaml.

flutter pub get

Dependency Resolution Flow

pubspec.yaml
      |
      v
Dependency Constraints
      |
      v
Version Solver
      |
      v
Compatible Versions
      |
      v
pubspec.lock
      |
      v
Packages Available to Project

11. Importing a Package

After adding a package, it can be imported into the Dart file where it is required.

import 'package:http/http.dart' as http;

The package can then be used in the application.

12. Example Using the http Package

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class ApiExample extends StatelessWidget {
  const ApiExample({super.key});

  Future<void> fetchUsers() async {
    final response = await http.get(
      Uri.parse('https://example.com/api/users'),
    );

    if (response.statusCode == 200) {
      print(response.body);
    } else {
      print('Request failed');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('API Example'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: fetchUsers,
          child: const Text('Fetch Users'),
        ),
      ),
    );
  }
}

13. Package Versioning

Packages use version numbers to identify different releases. A common version format is:

MAJOR.MINOR.PATCH

Example:
2.4.1
PartMeaning
MAJORMajor changes that may introduce breaking changes.
MINORNew backward-compatible functionality.
PATCHBug fixes and small compatible changes.

14. Caret Version Constraint

A common dependency version syntax is the caret constraint.

dependencies:
  http: ^1.0.0

The dependency solver can select a compatible version according to the declared constraint and Dart's versioning rules.

15. Version Range Constraints

Developers can also specify an explicit version range.

dependencies:
  example_package: '>=1.0.0 <2.0.0'

This specifies a version greater than or equal to 1.0.0 and less than 2.0.0.

16. pubspec.lock

The pubspec.lock file records the concrete dependency versions selected for the project, including transitive dependencies.

For application projects, keeping this file under version control helps ensure consistent dependency resolution across development environments.

17. Direct Dependencies

A direct dependency is a package that is explicitly added to the project's pubspec.yaml.

dependencies:
  http: ^1.0.0
  provider: ^6.0.0

Here, http and provider are direct dependencies.

18. Transitive Dependencies

A transitive dependency is a package required by another package.

Your Application
       |
       +-- Package A
              |
              +-- Package B
                     |
                     +-- Package C

Package B and Package C can be transitive dependencies of the application.

19. Dependency Resolution

Flutter uses Dart's package management system to resolve dependency constraints. The version solver attempts to find compatible versions for all direct and transitive dependencies.

Example

Package A
requires:
http: ^1.0.0

Package B
requires:
http: ^2.0.0

Project
uses:
Package A + Package B

If the requirements cannot be satisfied together, dependency resolution can fail and the developer may need to update or replace one of the packages.

20. Checking Outdated Packages

The following command helps identify dependencies for which newer versions are available.

flutter pub outdated

21. Updating Dependencies

To update dependencies within the declared constraints, use:

flutter pub upgrade

To update dependency constraints to newer major versions where possible, use:

flutter pub upgrade --major-versions

Major upgrades can introduce breaking changes, so the application should be tested after upgrading.

22. Common Flutter Packages

PackageCommon Purpose
httpHTTP requests and API communication.
providerState management and dependency injection patterns.
shared_preferencesSimple persistent key-value storage.
sqfliteSQLite database access.
firebase_coreFirebase initialization.
firebase_authFirebase authentication.
cloud_firestoreCloud Firestore database access.
url_launcherOpening URLs and external applications.
image_pickerSelecting images from supported device sources.
intlInternationalization and formatting.

23. Adding Multiple Dependencies

dependencies:
  flutter:
    sdk: flutter
  http: ^1.0.0
  provider: ^6.0.0
  shared_preferences: ^2.0.0
  intl: ^0.19.0

After saving the file, run:

flutter pub get

24. Local Package Dependency

A project can depend on a package stored locally using a path dependency.

dependencies:
  my_custom_package:
    path: ../my_custom_package

Path dependencies are useful when developing multiple related packages locally.

25. Git Dependency

A package can also be obtained directly from a Git repository.

dependencies:
  my_package:
    git:
      url: https://github.com/example/my_package.git

26. Dependency Overrides

The dependency_overrides section can be used to force a particular dependency version for the root project.

dependencies:
  package_a: ^1.0.0

dependency_overrides:
  package_b: ^2.0.0

Dependency overrides should be used carefully because they can hide compatibility problems.

27. Finding Packages

Flutter and Dart packages are commonly discovered through pub.dev. Before adding a package, developers should check its documentation, supported platforms, dependencies, version history, maintenance activity, license, examples, and SDK compatibility.

28. Steps to Select a Package

  1. Identify the required functionality.
  2. Search for suitable packages.
  3. Read the package documentation.
  4. Check the package version.
  5. Check Dart and Flutter SDK compatibility.
  6. Review supported platforms.
  7. Check dependencies.
  8. Review examples.
  9. Add the package.
  10. Run flutter pub get.
  11. Import and use the package.
  12. Test the application.

29. Complete Package Installation Example

Step 1: Create Project

flutter create package_demo
cd package_demo

Step 2: Add Package

flutter pub add http

Step 3: Import Package

import 'package:http/http.dart' as http;

Step 4: Use Package

Future<void> getData() async {
  final response = await http.get(
    Uri.parse('https://example.com/data'),
  );

  print(response.body);
}

Step 5: Run Application

flutter run

30. Packages in a Real-World Flutter Application

Flutter Application
       |
       +-- Networking
       |     +-- http
       |
       +-- State Management
       |     +-- provider
       |
       +-- Authentication
       |     +-- firebase_auth
       |
       +-- Database
       |     +-- cloud_firestore
       |
       +-- Local Storage
       |     +-- shared_preferences
       |
       +-- Device Features
             +-- image_picker
             +-- url_launcher

31. Benefits of Dependency Management

  • Maintains predictable project builds.
  • Controls package versions.
  • Helps manage package compatibility.
  • Makes team development easier.
  • Reduces duplicated code.
  • Provides access to reusable functionality.
  • Helps maintain a modular application architecture.

32. Best Practices

  • Choose packages that are suitable for the project.
  • Read package documentation before implementation.
  • Use appropriate version constraints.
  • Avoid unnecessary dependencies.
  • Regularly review outdated dependencies.
  • Test the application after dependency upgrades.
  • Be careful with major-version upgrades.
  • Understand transitive dependencies.
  • Use dependency overrides carefully.
  • Keep dependencies organized and documented.

33. Common Mistakes

MistakeProblemBetter Approach
Adding too many packagesIncreases project complexity.Add only necessary packages.
Ignoring version constraintsCan cause compatibility issues.Understand dependency requirements.
Never updating packagesProject may become outdated.Regularly review dependencies.
Blindly upgrading major versionsBreaking changes may occur.Read changelogs and test carefully.
Unnecessary dependency overridesCan hide compatibility issues.Use overrides carefully.
Ignoring documentationCan result in incorrect implementation.Read package documentation.

34. Important Commands

CommandPurpose
flutter pub add package_nameAdd a package.
flutter pub getGet project dependencies.
flutter pub remove package_nameRemove a dependency.
flutter pub outdatedCheck outdated dependencies.
flutter pub upgradeUpgrade dependencies within declared constraints.
flutter pub upgrade --major-versionsUpgrade dependency constraints to newer major versions where possible.
flutter cleanClean generated build files.

35. Troubleshooting Dependency Problems

Problem 1: Version Conflict

When packages require incompatible versions of the same dependency, the version solver may report an error.

Update compatible packages, adjust constraints where appropriate, or replace an incompatible package.

Problem 2: Package Not Found

Check the package name, network connection, package availability, and pubspec.yaml syntax.

Problem 3: Import Error

Target of URI doesn't exist

Make sure the dependency has been added correctly and run:

flutter pub get

Problem 4: Plugin Requires Restart

Some plugins contain platform-specific native code. Stop and restart the application after installing or changing such plugins.

36. Dependency Architecture

Presentation Layer
       |
       v
State Management
       |
       v
Repository / Service Layer
       |
       v
API / Database Package
       |
       v
External Service

For example, an application can use a state-management package for UI state, an HTTP package for REST APIs, and Firebase packages for authentication or cloud data.

37. Interview Questions

Q1. What is a Flutter package?

A Flutter package is reusable Dart or Flutter functionality that can be added to a project.

Q2. What is a dependency?

A dependency is an external package or library required by an application or another package.

Q3. What is pubspec.yaml?

pubspec.yaml is the project configuration file containing metadata, dependencies, SDK constraints, assets, fonts, and other settings.

Q4. What is flutter pub get?

It retrieves and resolves dependencies specified by the project.

Q5. What is pubspec.lock?

It records the concrete dependency versions selected for the project.

Q6. What is a direct dependency?

A direct dependency is explicitly declared by the project in pubspec.yaml.

Q7. What is a transitive dependency?

A transitive dependency is a dependency required by another package.

Q8. What is a plugin?

A plugin is a package that can provide access to platform-specific functionality.

Q9. How do you add a package?

flutter pub add package_name

Q10. How do you check outdated dependencies?

flutter pub outdated

38. Practical Project Example

Consider an e-commerce Flutter application. Different packages can be used for different application features.

FeaturePackage Category
Product APIHTTP/networking package
User AuthenticationAuthentication package
Cloud DatabaseDatabase/Firebase package
Local PreferencesLocal storage package
Image SelectionImage picker plugin
External LinksURL launcher plugin
Date FormattingInternationalization package

39. Summary

  • Flutter packages provide reusable functionality.
  • Dependencies are declared in pubspec.yaml.
  • flutter pub add can be used to add packages.
  • flutter pub get retrieves and resolves dependencies.
  • pubspec.lock records resolved dependency versions.
  • Direct dependencies are explicitly declared by the project.
  • Transitive dependencies are required by other packages.
  • Plugins can provide platform-specific functionality.
  • flutter pub outdated helps identify outdated packages.
  • flutter pub upgrade updates dependencies within their declared constraints.
  • Dependency conflicts should be resolved carefully.

Learn Flutter

JustAcademy Flutter Training Course

Register for Flutter Course Demo

Previous Next
whatsapp